package androidx.blogger.activities;

import com.google.gwt.user.client.rpc.AsyncCallback;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener; 
import androidx.blogger.BlogCollectionListModel;
import androidx.blogger.BlogRenderer;
import androidx.blogger.BloggerApplication;
import androidx.blogger.Log;
import androidx.blogger.LoginActivity;
import androidx.blogger.R;
import androidx.blogger.tasks.GetBlogCollectionTask;
import androidx.gdata.blogger.Blog;
import androidx.gdata.blogger.BlogCollection;
import androidx.list.ListAdapterFactory;

public class ShowUserBlogs extends ConnectedActivity {
  ListView blogsList;
  private Button newBlogBtn;
  private BlogCollectionListModel blogs = new BlogCollectionListModel();

  private static final int MENU_NEW_POST = Menu.FIRST;
  private static final int MENU_DELETE_BLOG = Menu.FIRST + 1;
  private static final int MENU_NEW_BLOG = Menu.FIRST + 2;
  private static final int MENU_PREFERENCES = Menu.FIRST + 3;
  private static final int MENU_CHANGE_IDENTITY = Menu.FIRST + 4;
  private static final int MENU_CHECK_FOR_UPDATES = Menu.FIRST + 5;

  /** Called when the activity is first created. */
  @Override
  protected void onCreate2(Bundle savedInstanceState) {
    setContentView(R.layout.user_blogs);
    setTitle("Select a Blog for " + BloggerApplication.getInstance().getUsername());

    blogsList = (ListView) findViewById(R.id.userblogs_listview);
    newBlogBtn = (Button) findViewById(R.id.newblog_btn);
    newBlogBtn.setOnClickListener(newBlogClickListener);
    blogsList.setAdapter( ListAdapterFactory.createAdapter(this, blogs, new BlogRenderer(this)) );
    blogsList.setOnItemClickListener(blogSelectionListener);
    blogsList.setOnCreateContextMenuListener(blogListContextMenuListener);
    fetchBlogs();
  }

  @Override
  public void onResume() {
    super.onResume();
    BloggerApplication.getInstance().setBlogEntryCollection(null);
  }

  /**
   * this method ensures this activity has a blog collection
   */
  private void fetchBlogs() {
    if (BloggerApplication.getInstance().getBlogCollection() == null)
      GetBlogCollectionTask.execute(getProgressIndicator("Getting list of blogs"), feedCallback);
    else
      onReceiveBlogCollection(BloggerApplication.getInstance().getBlogCollection());
  }

  /**
   * This method is called either directly from fetchBlogs in the case that we
   * have a cached blog collection, otherwise it will be called after asynchronously
   * fetching a blog collection.
   * 
   * @param blogCollection
   */
  private void onReceiveBlogCollection(BlogCollection blogCollection) {
    boolean noBlogs = (blogCollection.getBlogs() == null || blogCollection.getBlogs().length == 0);

    // if we have no blogs, make the "new blog" button visible so the end user doesn't just see
    // a blank screen
    if (noBlogs) {
      newBlogBtn.setVisibility(View.VISIBLE);
    } else {
      newBlogBtn.setVisibility(View.INVISIBLE);
    }

    // cache the current blog collection
    BloggerApplication.getInstance().setBlogCollection(blogCollection);
    // pass the blog collection to the list model
    blogs.setBlogCollection(blogCollection);
  }
  
  private View.OnClickListener newBlogClickListener = new View.OnClickListener() {
    public void onClick(View v) {
      createNewBlog();
    }
  };
  
  
  private OnCreateContextMenuListener blogListContextMenuListener =
      new OnCreateContextMenuListener() {
        public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenu.ContextMenuInfo menuInfo) {
          menu.setHeaderTitle("Blog Options");
          menu.add(0, MENU_NEW_POST, Menu.NONE, "New Post");
          menu.add(0, MENU_DELETE_BLOG, Menu.NONE, "Delete Blog");
        }
      };

  /** Process the context menu item selection */
  @Override
  public boolean onContextItemSelected(MenuItem item) {
    super.onContextItemSelected(item);

Log.i("onContextItemSelected");    
    switch (item.getItemId()) {
      case MENU_NEW_BLOG:
        createNewBlog();
        return true;
        
      case MENU_NEW_POST:
        onNewPostSelected(item);
        return true;

      case MENU_DELETE_BLOG:
        return true;
    }
    return false;
  }

  /** Process the options menu item selection */
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    Log.i("onOptionsItemSelected");    
    
    switch (item.getItemId()) {
      case MENU_NEW_BLOG:
        createNewBlog();
        return true;
        
      case MENU_PREFERENCES:
        return true;
        
      case MENU_CHANGE_IDENTITY:
        changeIdentity();
        return true;
        
      case MENU_CHECK_FOR_UPDATES:
      	checkForUpdate();
      	return true;
    }
    return false;
  }
  
  private void checkForUpdate() {
    Intent intent = new Intent();
    intent.setData(Uri.parse(BloggerApplication.ABLOGGER_APPLICATION_URI));
    try {
      startActivity(intent);
    } catch (ActivityNotFoundException anfe2) {
      longMessage("Android Market not found!");
    }
  }
  
  
  private void changeIdentity() {
    BloggerApplication.getInstance().reset();
    Intent intent = new Intent(this, LoginActivity.class);
    startActivity(intent);
    finish();
  }
  
  
  private void createNewBlog() {
//    String url = "http://www.blogger.com/signup.g";
    String url = "https://www.google.com/accounts/Login?service=blogger&naui=8&continue=https%3A%2F%2Fwww.blogger.com%2Floginz%3Fd%3D%252Fcreate-blog.g%26a%3DADD_SERVICE_FLAG&alwf=true&skipvpage=true&Email="
      + BloggerApplication.getInstance().getUsername();
    Log.i("Opening " + url);
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    startActivity(intent);
    // reset our blog collection so it gets re-fetched
    BloggerApplication.getInstance().setBlogCollection(null);
    finish();
  }  
  
  private void onNewPostSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo menuInfo =
        (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    Blog chosenBlog = BloggerApplication.getInstance().getBlogCollection().getBlogs()[menuInfo.position];
    BloggerApplication.getInstance().setCurrentBlog(chosenBlog);
    BloggerApplication.getInstance().setCurrentPost(null);
    Intent intent = new Intent(this, EditBlogPost.class);
    startActivity(intent);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    menu.add(Menu.NONE, MENU_NEW_BLOG, Menu.NONE, "Add New Blog").setIcon(
        android.R.drawable.ic_menu_add);
//    menu.add(Menu.NONE, MENU_PREFERENCES, Menu.NONE, "Settings").setIcon(
//        android.R.drawable.ic_menu_preferences);
    menu.add(Menu.NONE, MENU_CHECK_FOR_UPDATES, Menu.NONE, "Check for updates").setIcon(
        android.R.drawable.ic_menu_search);
    menu.add(Menu.NONE, MENU_CHANGE_IDENTITY, Menu.NONE, "Change Identity").setIcon(
        android.R.drawable.ic_media_rew);
    return true;
  }


  private OnItemClickListener blogSelectionListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
      Blog chosenBlog = BloggerApplication.getInstance().getBlogCollection().getBlogs()[position];
      onBlogChosen(chosenBlog);
    }
  };



  private void onBlogChosen(Blog blog) {
    BloggerApplication.getInstance().setCurrentBlog(blog);
    Intent intent = new Intent(this, ShowUserBlog.class);
    startActivity(intent);
  }


  private AsyncCallback<BlogCollection> feedCallback = new AsyncCallback<BlogCollection>() {
    public void onSuccess(BlogCollection result) {
      onReceiveBlogCollection(result);
    }

    public void onFailure(Throwable t) {
      longMessage("Error getting blogs");
    }
  };

}
